package com.example.demo.config;

import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 作者 zj:
 * @version 创建时间：2019年2月1日 上午11:44:15
 * 类说明
 */
@Slf4j
public class DBContextHolder {
	
	private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
	
	private static final AtomicInteger counter = new AtomicInteger(-1);
	
	public static void set(DBTypeEnum dbType){
		contextHolder.set(dbType);
		log.info("切换到 "+dbType.name());
	}
	
	public static DBTypeEnum get(){
		return contextHolder.get();
	}
	
	public static void master(){
		set(DBTypeEnum.MASTER);
	}
	
	public static void slave(){
		//轮询
		int index = counter.getAndIncrement() % 2;
		if(counter.get()>9999){
			counter.set(-1);
		}
		if (index == 0) {
            set(DBTypeEnum.SLAVE1);
        }else {
            set(DBTypeEnum.SLAVE2);
        }
	}

}
